import { request } from 'https'
import { parse } from 'url'

export default async function handler(req, res) {
  const { recaptcha } = req.body

  const secret_key = '6LfPUMQpAAAAAJv2h6bz0Sh7QhAW720M8VJgWSt-'
  const apiUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${recaptcha}`

  const data = JSON.stringify({ response: recaptcha })

  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': data.length
    }
  }

  const apiUrlParts = parse(apiUrl, true)
  options.hostname = apiUrlParts.hostname
  options.path = apiUrlParts.path

  return new Promise((resolve, reject) => {
    const req = request(options, resp => {
      let data = ''

      resp.on('data', chunk => {
        data += chunk
      })

      resp.on('end', () => {
        const parsedData = JSON.parse(data)
        if (parsedData.success) {
          res.status(200).json({ success: true })
        } else {
          res.status(200).json({ success: false })
        }
        resolve()
      })

      resp.on('error', error => {
        reject(error)
      })
    })

    req.write(data)
    req.end()
  })
}
